/*************************************************************************
	> File Name: tcp_servser.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/04 12:03
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include "log.hpp"

const int SIZE = 1024;

class TcpServer
{
public:
    TcpServer (const uint16_t& port, const std::string& ip = "0.0.0.0"):_ip(ip), _port(port), _listensock(-1)
    {}

    bool initServer()
    {
        if ((_listensock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            logMessage(FATAL, "socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if (bind(_listensock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
        if (listen(_listensock, gbacklog) < 0) {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "listen success");
        return true;
    }

    void start()
    {
        while (1) {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            int serversock = accept(_listensock, (struct sockaddr*)&src, &len);
            if (serversock < 0) {
                logMessage(ERROR, "link error, %d:%s", errno, strerror(errno));
                continue;
            }
            uint16_t cli_port = ntohs(src.sin_port);
            std::string cli_ip = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "link success, %d, %s:%d", serversock, cli_ip.c_str(), cli_port);
            if (fork() == 0) {
                close(_listensock);
                if (fork() > 0) {
                    exit(0);
                }
                routine(serversock, cli_ip, cli_port);
                exit(0);
            }
            close(serversock);
        }
    }

private:
    static void routine(const int sock, const std::string& ip, const uint16_t& port)
    {
        char buffer[SIZE];
        char result[SIZE];
        while (1) {
            memset(&buffer, 0, sizeof buffer);
            ssize_t s = read(sock, &buffer, sizeof buffer - 1);
            if (s > 0) {
                logMessage(NORMAL, "read success");
                FILE *fp = popen(buffer, "r");
                if (nullptr == fp) {
                    logMessage(ERROR, "popen error");
                    break;
                }
                logMessage(NORMAL, "get cmd-line:\n%s, from %s:%d", buffer, ip.c_str(), port);
                std::string sendMessage;
                while (fgets(result, sizeof result, fp)) {
                    sendMessage += result;
                }
                write(sock, sendMessage.c_str(), sendMessage.size());
            } else if (s == 0) {
                logMessage(NORMAL, "client %s:%d shutdown, the server will shutdown", ip.c_str(), port);
                break;
            } else {
                logMessage(ERROR, "read error, %s:%d", ip.c_str(), port);
                break;
            }
        }
        close(sock);
    }

    int _listensock;
    static const int gbacklog = 20;
    uint16_t _port;
    std::string _ip;
};
